package com.linktel.productionLine.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.github.pagehelper.PageInfo;
import com.linktel.productionLine.EasyExcel.CommentCellWriteHandler;
import com.linktel.productionLine.EasyExcel.dailyAttendance.DailyAttendanceListener;
import com.linktel.productionLine.EasyExcel.dailyAttendance.model.WriteDailyAttendance;
import com.linktel.productionLine.EasyExcel.util.Methods;
import com.linktel.productionLine.common.BaseContext;
import com.linktel.productionLine.common.BaseResponse;
import com.linktel.productionLine.common.ErrorCode;
import com.linktel.productionLine.common.ResultUtils;
import com.linktel.productionLine.dao.DailyAttendanceDao;
import com.linktel.productionLine.dao.ProductionLineDao;
import com.linktel.productionLine.entity.dto.dailyAttendance.AttendanceInfoDTO;
import com.linktel.productionLine.entity.query.dailyAttendance.AddAttendanceInfoQuery;
import com.linktel.productionLine.entity.query.dailyAttendance.DeleteAttendanceInfoQuery;
import com.linktel.productionLine.entity.query.dailyAttendance.EditAttendanceInfoQuery;
import com.linktel.productionLine.entity.query.dailyAttendance.ListAttendanceInfoQuery;
import com.linktel.productionLine.exception.BusinessException;
import com.linktel.productionLine.service.DailyAttendanceService;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author HuangJiaHui
 * @Date 2023/9/3 16:52
 */
@RestController
@RequestMapping("/daily")
@AllArgsConstructor
public class DailyAttendanceController {
    private DailyAttendanceService dailyAttendanceService;

    private DailyAttendanceDao dailyAttendanceDao;
    private ProductionLineDao productionLineDao;

    /**
     * 根据用户id，展示对应产线的日出勤数据
     *
     * @param listAttendanceInfoQuery 用户id
     * @return 日出勤数据列表
     */
    @GetMapping("/attendanceInfo")
    public BaseResponse<PageInfo<AttendanceInfoDTO>> listAttendanceInfo(ListAttendanceInfoQuery listAttendanceInfoQuery) {
        if (listAttendanceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        PageInfo<AttendanceInfoDTO> attendanceInfoDTOS = dailyAttendanceService.listAttendanceInfo(listAttendanceInfoQuery);
        return ResultUtils.success(attendanceInfoDTOS);
    }

    /**
     * 新增日出勤数据
     *
     * @param addAttendanceInfoQuery 新增的日出勤数据封装
     * @return 是否新增成功
     */
    @PostMapping("/attendanceInfo")
    public BaseResponse<Boolean> addAttendanceInfo(@RequestBody AddAttendanceInfoQuery addAttendanceInfoQuery) {
        if (addAttendanceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = dailyAttendanceService.addAttendanceInfo(addAttendanceInfoQuery);
        return ResultUtils.success(result);
    }

    /**
     * 修改日出勤数据
     *
     * @param editAttendanceInfoQuery 修改的日出勤数据封装
     * @return 是否修改成功
     */
    @PutMapping("/attendanceInfo")
    public BaseResponse<Boolean> editAttendanceInfo(@RequestBody EditAttendanceInfoQuery editAttendanceInfoQuery) {
        if (editAttendanceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = dailyAttendanceService.editAttendanceInfo(editAttendanceInfoQuery);
        return ResultUtils.success(result);
    }

    /**
     * 删除日出勤数据
     *
     * @param deleteAttendanceInfoQuery 删除日出勤数据封装
     * @return 是否删除成功
     */
    @DeleteMapping("/attendanceInfo")
    public BaseResponse<Boolean> deleteAttendanceInfo(@RequestBody DeleteAttendanceInfoQuery deleteAttendanceInfoQuery) {
        if (deleteAttendanceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = dailyAttendanceService.deleteAttendanceInfo(deleteAttendanceInfoQuery);
        return ResultUtils.success(result);
    }

    /**
     * 下载excel文件，内容包括筛选查询后的全部数据
     *
     * @param listAttendanceInfoQuery 筛选查询出勤数据的封装对象
     */
    @GetMapping("/attendanceInfo/download")
    public void downloadAttendanceData(ListAttendanceInfoQuery listAttendanceInfoQuery, HttpServletResponse response) {
        if (listAttendanceInfoQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<WriteDailyAttendance> writeDailyAttendances = dailyAttendanceService.downloadAttendanceDate(listAttendanceInfoQuery);
        try {

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 防止中文乱码
            String fileName = URLEncoder.encode("日出勤基础数据", "UTF-8")
                    .replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ExcelTypeEnum.XLSX.getValue());
            //响应的输入流
            ServletOutputStream outputStream = response.getOutputStream();
            // workbook
            ExcelWriterBuilder writeWorkBook = EasyExcel.write(outputStream, WriteDailyAttendance.class).inMemory(Boolean.TRUE)
                    .head(WriteDailyAttendance.class)
                    .useDefaultStyle(false)
                    .registerWriteHandler(new CommentCellWriteHandler(Methods.getNotationMap(WriteDailyAttendance.class)));// 添加备注的监听器
            // sheet
            writeWorkBook.sheet().sheetName("日出勤基础数据").sheetNo(0).doWrite(writeDailyAttendances);
            outputStream.flush();
            outputStream.close();
        } catch (IOException | IllegalArgumentException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "导出失败");
        }
    }

    /**
     * 上传excel文件，批量保存日出勤基础数据
     *
     * @param file          excel文件
     * @param currentUserId 当前用户Id
     * @return 是否插入成功
     */
    @PostMapping("/attendanceInfo/upload")
    public BaseResponse<String> upload(@Param("file") MultipartFile file, Long currentUserId) {
        if (file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传数据为空");
        }
        try {
            EasyExcel.read(file.getInputStream(), WriteDailyAttendance.class, new DailyAttendanceListener(dailyAttendanceDao, currentUserId, productionLineDao, dailyAttendanceService)).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        String currentLog = BaseContext.getCurrentLog();
        return ResultUtils.success(currentLog);
    }

}
